"""--------------------------------------------------------------------------------------------------
Filename:   handlers.py
Author:     Chris Chester(christopher.chester@pg.canterbury.ac.nz) adapted from work 
                                                done by Ben Han (uha10@uclive.ac.nz)
Date:       26th July 2012
Description:
    Module for the GUI event handlers
--------------------------------------------------------------------------------------------------"""

import wx
import csv
import os, sys, traceback
import pickle, copy
from database import Patient, SessionRecord
from config import ConfigPanel
from bioimped_serial import Console
from serialFind import SerialFind
import time



#===============================================================================
# CLASS: MainHandlers
#    Contains event handlers for the main window
#===============================================================================
class MainHandlers:
    def __init__(self, app):
        # Save references to main objects
        self.app = app
        
    def new_patient(self, event):
        ''' Create new patient object. 
        Return value is a boolean indicating whether a patient file was written to disk '''
        cpat = Patient(sessions=[])
        
        # Set the current working directory to the user's home directory by default
        ddir = str(wx.GetHomeDir()) + "/BISSKIT"
        try:
            os.makedirs(ddir)   # create the default save directory
        except OSError:
            pass    # path already exists
        except:
            sys.stderr.write(traceback.format_exc())
            
        os.chdir(ddir)
        
        dfile = str(cpat.id)    # default filename set to ID
        file_choices = "Patient files (*.pat)|*.pat"
        dlg = wx.FileDialog(self.app.main_frame,
                            message="Choose a location for the new patient file",
                            defaultDir=os.getcwd(),
                            defaultFile=dfile,
                            wildcard=file_choices,
                            style=wx.FD_OPEN)

        if dlg.ShowModal() == wx.ID_OK:
            cpat.path = dlg.GetPath()       # store path to file in patient object
            
            if os.path.exists(cpat.path):
                # path already exists, ask user to overwrite current files
                msg = "The selected path already exists.\nOverwrite the existing patient file?"
                dlg2 = wx.MessageDialog(None, msg, "Patient file query", wx.ICON_QUESTION | wx.YES_NO | wx.NO_DEFAULT)
                if dlg2.ShowModal() == wx.ID_YES:
                    pass
                else:
                    # if the answer is no then cancel
                    return False
            try:
                tempFile = open(cpat.path, 'wb')
                pickle.dump(cpat, tempFile, pickle.HIGHEST_PROTOCOL)
                tempFile.close()
            except:
                msg = ">> Error saving patient object to file.\n"
                sys.stderr.write(msg)
                wx.MessageDialog(None, msg, "Patient file error", wx.ICON_WARNING | wx.OK).ShowModal()
                sys.stderr.write(traceback.format_exc())
            else:   # file successfully opened
                self.app.status.patient = cpat
                self.app.cfg = cpat.cfg
                self.app.main_frame.update_patient_panel()
                self.app.status.patient_changed = False
                msg = ">> New patient saved to: %s  -- Date: %s\n" % (cpat.path, wx.DateTime.Now().Format())
                self.app.status_msg(msg)
                sys.stdout.write(msg)
                # Create a directory for sessions, same name as patient file
                try:
                    fname = str(dlg.GetFilename())[:-4]
                    ddir = str(dlg.GetDirectory()) + "/" + fname + "_sessions"
                    os.makedirs(ddir)
                except OSError:
                    pass    # directory already exists
                except:
                    sys.stderr.write(traceback.format_exc())
                return True
        
    def open_patient(self, event):
        ''' Open previously saved patient object'''
        # Set the current working directory to the user's home directory by default
        ddir = str(wx.GetHomeDir()) + "/BISSKIT"
        if not os.path.isdir(ddir):
            try:
                os.makedirs(ddir)   # create the default save directory
            except OSError:
                pass    # path already exists
            except:
                sys.stderr.write(traceback.format_exc())
        os.chdir(ddir)
        
        file_choices = "Patient files (*.pat)|*.pat"
        dlg = wx.FileDialog(self.app.main_frame,
                            message="Open existing patient file",
                            defaultDir=os.getcwd(),
                            wildcard=file_choices,
                            style=wx.FD_OPEN)

        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()    # path to patient file
            try:
                tempFile = open(path, 'rb')
                cpat = self.app.status.patient = pickle.load(tempFile)
                tempFile.close()
            except:
                msg = "Error loading patient object from file.\n"
                sys.stderr.write(msg)
                wx.MessageDialog(None, msg, "Patient file error", wx.ICON_WARNING | wx.OK).ShowModal()
                sys.stderr.write(traceback.format_exc())
            else:
                cpat.path = path        # store path to file in patient object
                self.app.cfg = cpat.cfg
                self.app.cfg._y_axis_max = self.app.cfg.Y_AXIS_MAX_INIT
                self.app.main_frame.update_patient_panel()
                self.app.main_frame.status_message("Loaded patient file: %s" % path)
                self.app.status.patient_changed = False
                msg = ">> Patient loaded from: %s  -- Date: %s\n" % (path, wx.DateTime.Now().Format())
                self.app.status_msg(msg)
                sys.stdout.write(msg)
            
    def save_patient(self, event):
        ''' Save currently loaded patient to file'''
        cpat = self.app.status.patient
        cpat.cfg = self.app.cfg
        if cpat == None:
            self.app.status_msg('No patient loaded')
        else:
            # Set patient object attributes from wx controls
            self.app.main_frame.set_patient_attr()
                
            # Open a save file dialog to set the path
            dfile = copy.copy(cpat.path)
            file_choices = "Patient files (*.pat)|*.pat"
            dlg = wx.FileDialog(self.app.main_frame,
                                message="Save current patient to file",
                                defaultFile=dfile,
                                wildcard=file_choices,
                                style=wx.FD_SAVE)
    
            if dlg.ShowModal() == wx.ID_OK:
                cpat.path = dlg.GetPath()
                try:
                    # open a file object using the provided path and pickle the patient object
                    tempFile = open(cpat.path, 'wb')
                    pickle.dump(cpat, tempFile, pickle.HIGHEST_PROTOCOL)
                    tempFile.close()
                except:
                    msg = "Error saving patient object to file.\n"
                    sys.stderr.write(msg)
                    wx.MessageDialog(None, msg, "Patient file error", wx.ICON_WARNING | wx.OK).ShowModal()
                    sys.stderr.write(traceback.format_exc())
                else:
                    self.app.status.patient_changed = False
                    msg = ">> Patient file saved to: %s  -- Date: %s\n" % (cpat.path, wx.DateTime.Now().Format())
                    self.app.status_msg(msg)
                    sys.stdout.write(msg)
                    # Create a directory for sessions, same name as patient file
                    fname = str(dlg.GetFilename())[:-4]
                    ddir = str(dlg.GetDirectory()) + "/" + fname + "_sessions"
                    # Create a folder for sessions if it doesn't already exist
                    if not os.path.isdir(ddir):
                        try:
                            os.makedirs(ddir)
                        except OSError:
                            pass    # directory already exists
                        except:
                            sys.stderr.write(traceback.format_exc())
         
    def patient_changed(self, event):
        ''' Set patient object attributes from wx controls'''
        self.app.main_frame.set_patient_attr()
        self.app.status.patient_changed = False
        
    def export_patient(self, event):
        ''' Export the patient statistics to a .csv file '''
        try:
            pat = self.app.status.patient
            path = ""
            if len(pat.session_record) > 0:
                path = pat.export(self.app.main_frame)
                
            if path == "":
                pass    # export cancelled
            else:
                msg = 'Patient:\n    %s-%s\nExported to:\n    %s\n' % (pat.id, pat.name, path)
                sys.stdout.write(msg)
                wx.MessageDialog(None, msg, "Export Patient to CSV files", wx.ICON_INFORMATION | wx.OK).ShowModal()
        except:
            msg = 'Error exporting patient record to CSV files.\n'
            self.app.status_msg(msg)
            sys.stderr.write(msg)
            wx.MessageDialog(None, msg, "Patient file error", wx.ICON_WARNING | wx.OK).ShowModal()
            sys.stderr.write(traceback.format_exc())
            
    def config(self, event):
        ''' The event handler for the configuration button '''
        self.app.config_panel = ConfigPanel(parent=self.app.main_frame, cfg=self.app.cfg)
        self.app.config_panel.cfg_update()
        self.app.config_panel.MakeModal(True)
        self.app.config_panel.Show()
        
    def new_session(self, event):
        ''' The event handler for the start session button '''
        if self.app.status.patient == None:
            self.app.main_frame.status_message('No patient loaded')
        else:
            self.app.main_frame.set_patient_attr()
            self.app.setup_session()
            msg = '>>> New session started at: %s\n' % wx.DateTime.Now().Format()
            sys.stdout.write(msg)
        
    def session_select(self, event):
        ''' Event handler for User clicking on a row in the session listing'''
        
        ''' Currently does nothing '''
        cpat = self.app.status.patient
        try:
            self.row = event.GetRow()    # selected session index
            nsessions = len(cpat.session_record)
            if nsessions == 0:
                pass
            elif self.row < nsessions:
                # set the currently displayed session to the one selected
                # load session from file
                cpat = self.app.status.patient
                s_rec = cpat.session_record[self.row]
                i = cpat.path.rfind('\\')
                path = s_rec.path
                try:
                    tempFile = open(path, 'rb')
                    self.app.status.session_disp = pickle.load(tempFile)
                    tempFile.close()
                except:
                    msg = ">> Error loading session from file.\n"
                    sys.stderr.write(msg)
                    wx.MessageDialog(self.app.plot, msg, "Session load error", wx.ICON_WARNING | wx.OK).ShowModal()
                    sys.stderr.write(traceback.format_exc())

                self.app.main_frame.update_session_pane()
        except:
            print traceback.format_exc()
            

    def view_session(self, event):
        ''' Event Handler for exporting a session, exports a .csv file'''
        try:
            cpat = self.app.status.patient
            sess = self.app.status.session_disp
            ppath = cpat.path
            
            path = "%s_sessions\session_%s.csv" % (ppath[:-4], str(self.row +1))
            if path == "":
                pass        # export cancelled
            else:
                sys.stdout.write(path)
                f = open(path, 'rb')

                reader = csv.reader(f,quoting=csv.QUOTE_NONE)
                
                self.loaded_xvalues1 = [float(i) for i in reader.next()]
                self.loaded_yvalues1 = [float(i) for i in reader.next()]
                self.loaded_xvalues2 = [float(i) for i in reader.next()]
                self.loaded_yvalues2 = [float(i) for i in reader.next()]
                
                if(len(self.loaded_xvalues1) > 0):            
                    self.app.review_session()
                else:
                    msg = "No Data in Session"
                    wx.MessageDialog(None, msg, "Session object error", wx.ICON_WARNING | wx.OK).ShowModal() 

                # Need to create a new file for viewing the files
        except:
            msg = ">> Error exporting session.\n"
            sys.stderr.write(msg)
            wx.MessageDialog(None, msg, "Session object error", wx.ICON_WARNING | wx.OK).ShowModal()
            sys.stderr.write(traceback.format_exc())
                
    def exit(self, event):
        ''' Event Handler for clicking the exit button'''
        self.app.on_exit(event)
    
    def about(self, event):
        ''' Event Handler for clicking the about button'''
        from dialogs import AboutDialog
        AboutDialog(self.app.main_frame)
    


#===============================================================================
# CLASS: PlotHandlers
#    Contains event handlers for the control panel
#===============================================================================
class PlotHandlers:
    
    DEVICE_CODE = "\Device\VCP0"
    COM_PORT_POSITION = 1
    
    def __init__(self, app):
        # Save a reference to the main application object
        self.app = app
        self.pause_time = 0
        
    def start_sess_button(self, event):
        ''' Event Handler for the start session button in plot controls '''
        butt_ctrl = self.app.ctrl.but_ctrl
        plot_ctrl = self.app.plot.plotctrl
        s_state = self.app.sess_status
        self.app.sess_status.saved = False
        if not s_state.serial_open:
            self.app.status_msg("Serial port is not open")    
        else:
            sys.stdout.write(">> Start trials\n")
            s_state.alive = True
            self.app.worker.parse = True        # start processing jobs in the queue
                    
            self.app.plot.init_plot()
        
        # Change button label and enable/disable buttons
        label = "Start"

        butt_ctrl.start_sess_button.Disable()
        plot_ctrl.start_sess_button.Disable()
        plot_ctrl.pause_button.Enable()
        plot_ctrl.save_button.Enable()

        butt_ctrl.start_sess_button.SetLabel(label)
        plot_ctrl.start_sess_button.SetLabel(label)
        
        self.app.plot.draw()
        
        
    def pause(self, event):
        ''' Event Handler for the pause button in the plot controls '''
        plot_ctrl = self.app.plot.plotctrl
        # toggles the sess_status.alive variable to stop and start the plot
        if self.app.sess_status.alive:
            msg = "> Plot paused at: %s\n" % wx.DateTime.Now().Format()
            self.app.status_msg(msg)
            sys.stderr.write(msg)
            self.app.sess_status.alive = False      # stop adding jobs to the queue
            # Plot data acquired while paused is meaningless, so discard any jobs waiting in the queue
            self.app.worker.parse = False
            self.pause_time = time.time()
            plot_ctrl.pause_button.SetLabel('Continue')

        else:
            msg = "> Plot unpaused at: %s\n" % wx.DateTime.Now().Format()
            self.app.status_msg(msg)
            sys.stderr.write(msg)
            self.app.sess_status.alive = True
            self.app.worker.parse = True        # start processing jobs in the queue
            self.app.plot.start_time +=  time.time() - self.pause_time  # Adjust the time to continue from the same point
            plot_ctrl.pause_button.SetLabel('Pause')

        self.app.plot.draw()
        
    def save_exit(self, event):
        ''' Event handler for the save and exit button in the plot controls '''
        
        self.save_sess(event)
        self.exit_plot(event)
        
    def save_sess(self, event):
        ''' Event handler for saving the data '''
        # Save session to patient and file
        plot = self.app.plot 
        cpat = self.app.status.patient
        sess = self.app.status.session
        nsess = len(cpat.session_record) + 1
        
        # Save session object to file at the default location
        # default location is: \path-to-patient-dir\patient-filename_sessions\sess#_session-timestamp
        ppath = cpat.path
        path = "%s_sessions/session_%s.csv" % (ppath[:-4], str(nsess))
        ofile = open(path, 'wb')
        writer = csv.writer(ofile, dialect='excel')
        
        # Stores all of the data for saving
        plot.store_data()
        # Length of session
        self.app.status.session.sess_time = "Session Time:  " + str(round( time.time() - self.app.plot.start_time,0)) +"s"
                
        writer.writerow(plot.ch1_x_data_total)
        writer.writerow(plot.ch1_y_data_total)
        writer.writerow(plot.ch2_x_data_total)
        writer.writerow(plot.ch2_y_data_total)
        
        
        path = "%s_sessions/%s_%s.sess" % (ppath[:-4], str(nsess), self.app.status.session.timestamp)
        try:
            tempFile = open(path, 'wb')
            pickle.dump(sess, tempFile, pickle.HIGHEST_PROTOCOL)
            tempFile.close()
        except:
            msg = ">> Error saving session to file.\n"
            sys.stderr.write(msg)
            wx.MessageDialog(self.app.plot, msg, "Save session error", wx.ICON_WARNING | wx.OK).ShowModal()
            sys.stderr.write(traceback.format_exc())
        else:
            self.app.sess_status.saved = True
            s_rec = SessionRecord(sess)     # create a session record object for the current session
            # Find the index of the second rightmost "\" character in path
            i1 = path.rfind("/")
            i2 = path.rfind("/",0,i1)
            # Stored the path from the directory in which the patient file is stored
            s_rec.path = path[i2+1:]
            self.app.status.patient.add_session(s_rec)  # add record to the patient
            self.app.status.patient_changed = True
            
            try:
                # open a file object using the provided path and pickle the patient object
                tempFile = open(ppath, 'wb')
                pickle.dump(cpat, tempFile, pickle.HIGHEST_PROTOCOL)
                tempFile.close()
            except:
                msg = "Error saving patient object to file.\n"
                sys.stderr.write(msg)
                wx.MessageDialog(None, msg, "Patient file error", wx.ICON_WARNING | wx.OK).ShowModal()
                sys.stderr.write(traceback.format_exc())
            else:
                self.app.status.patient_changed = False

                msg = ">> Patient file saved to: %s  -- Date: %s\n" % (cpat.path, wx.DateTime.Now().Format())
                self.app.status_msg(msg)
                sys.stdout.write(msg)
    
    def exit_plot(self, event):
        ''' This function is run when the Main Menu button is clicked
            Closes the control panel and plot windows then returns to the main
            menu dialog. '''
        
        if (self.app.sess_status.saved == False):
            dialog_text = "Save session data?"
            dial = wx.MessageDialog(None, dialog_text, 'Question',
                                    wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
            ret = dial.ShowModal()
            if ret == wx.ID_YES:
                self.save_sess(event)
                msg = ">>> Session ended manually at:" + wx.DateTime.Now().Format()
                self.app.status_msg(msg)
                print '>> Session saved'
                print msg
        
        self.app.cfg._y_axis_max = self.app.cfg.Y_AXIS_MAX_INIT      # reset plot y axis max for the next session
        self.serial_disconnect(None)        # disconnect serial port
        self.app.serial_loop_closed.wait()  # wait for serial loop to close before destroying plot object in restroe_mainmenu()
        self.app.status.session = None      # reset reference to current session object
        self.app.sess_status = None         # reset reference to current session state object
        self.app.restore_mainmenu()
    
    def serial_port_change(self, event):
        ''' Event handler for changing the serial port '''
        print 'COM' + str(event.GetInt())
        self.app.cfg.port = 'COM' + str(event.GetInt())
        
                      
    def auto_connect(self,event):
        ''' Automatically finds the serial port with sEWMG on it'''

        serialFind = SerialFind()
        ports_list = serialFind.enumerate_serial_ports()
        port = "none"
        
        #Searches active ports for the one with the same name as the device
        for i in range(0, ports_list.__len__()):
            if str(ports_list[i][0]) == self.DEVICE_CODE:  
                port =  ports_list[i][self.COM_PORT_POSITION]
                break
        
        
        #Allocates appropriate COM port to the pySerial, if it exists
        if port == "none":
            msg = "Auto connect didn't work.\nCheck connection or connect manually."
            wx.MessageDialog(self.app.plot, msg, "Serial communication error", wx.ICON_WARNING | wx.OK).ShowModal()
            
            
            self.app.restore_mainmenu()
            #Reopen Connect Window
            self.app.main_frame.set_patient_attr()
            self.app.setup_session()
        else: 
            self.app.cfg.port = port
            self.serial_connect(event)
            #Disables if connected


    def serial_connect(self, event):
        ''' Connects to the port specified in self.app.cfg.port'''
        SERIAL_CHECK_TIME = 500  # Time between serial port check, in ms
        
        ser_ctrl = self.app.ctrl.serial_ctrl
        butt_ctrl = self.app.ctrl.but_ctrl
        plot_ctrl = self.app.plot.plotctrl
        # Handler for connect button in control panel
        # Start serial thread
        if not self.app.sess_status.serial_open:
            try:
                # Create a serial connection to the selected COM port
                self.app.console = Console(self.app.plot.update_data, self.app.cfg.port, self.app.serial_loop_closed,self.app)
            except:
                msg = "Error opening serial channel for communication with EMG device.\nPlease check connections and settings.\n"
                sys.stderr.write(msg)
                wx.MessageDialog(self.app.plot, msg, "Serial communication error", wx.ICON_WARNING | wx.OK).ShowModal()
                
                #Close plot window
                self.app.restore_mainmenu()
            
                #Reopen Connect Window
                self.app.main_frame.set_patient_attr()
                self.app.setup_session()
            else:       # if the serial port was successfully opened then:
                self.app.sess_status.serial_open = True
                ser_ctrl.connected_text.SetLabel("True")
                ser_ctrl.connected_text.SetForegroundColour(wx.Colour(0, 255, 0))
                ser_ctrl.button_disconnect.Enable()
                ser_ctrl.button_connect.Disable()
                ser_ctrl.button_auto_connect.Disable()
                butt_ctrl.start_sess_button.Enable()
                plot_ctrl.start_sess_button.Enable()
                plot_ctrl.pause_button.Enable()
            
                
                # check the serial port every 500ms to see if it is still open
                self.serial_check_timer = wx.Timer(self.app.ctrl, 52)
                self.app.ctrl.Bind(wx.EVT_TIMER, self.serial_check, self.serial_check_timer)
                self.serial_check_timer.Start(SERIAL_CHECK_TIME)
                
                # Making sure the plot doesn't start
                self.app.sess_status.alive = False
        else:
            pass    # if serial is already open, connect button should be disabled anyway
        return self.app.sess_status.serial_open
    
    def serial_check(self, event):
        ''' Checks if the serial port is open or not '''
        self.app.serial_lock.acquire()      # ACQUIRE SERIAL_LOCK <--
        
        if self.app.sess_status.serial_open:
            if self.app.serial_loop_closed.is_set():
                self.serial_disconnect(event)
                msg = "Serial port closed unexpectedly.\nPlease check connections.\n"
                sys.stderr.write(msg)
                wx.MessageDialog(self.app.plot, msg, "Serial communication error", wx.ICON_WARNING | wx.OK).ShowModal()
                
        self.app.serial_lock.release()      # RELEASE SERIAL_LOCK <--
    
    def serial_disconnect(self, event):
        ''' Disconnect from the currently connected serial port'''
        self.app.serial_lock.acquire()      # ACQUIRE SERIAL_LOCK <--
        
        ser_ctrl = self.app.ctrl.serial_ctrl
        butt_ctrl = self.app.ctrl.but_ctrl
        plot_ctrl = self.app.plot.plotctrl
        # Handler for disconnect button in control panel
        if self.app.sess_status.serial_open:
            if self.app.console == None:
                pass
            else:
                try:
                    self.serial_check_timer.Stop()  # stop checking the serial port
                    self.app.console.stop()
                except:
                    print traceback.format_exc()
                else:       # if the serial port was successfully stopped then:
                    self.app.sess_status.serial_open = False
                    ser_ctrl.connected_text.SetLabel("False")
                    ser_ctrl.connected_text.SetForegroundColour(wx.Colour(255, 0, 0))
                    ser_ctrl.button_disconnect.Disable()
                    ser_ctrl.button_connect.Enable()
                    ser_ctrl.button_auto_connect.Enable()
                    butt_ctrl.start_sess_button.Disable()
                    plot_ctrl.start_sess_button.Disable()
                    plot_ctrl.pause_button.Disable()
                    
        self.app.serial_lock.release()      # RELEASE SERIAL_LOCK <--
        return self.app.sess_status.serial_open

#===============================================================================
# CLASS: PlotHandlers
#    Contains event handlers for reviewing previous data
#===============================================================================
class ReviewHandlers:
    def __init__(self, app):
        # Save a reference to the main application object
        self.app = app
        self.xmin = 0
        self.index = 0 # Position in the data to display from 
        self.shift_value = 5 # Amount that is shift
        self.xwidth = 10 # Width in seconds of the display
        
         
    def exit_review_plot(self,event):
        self.app.cfg._y_axis_max = self.app.cfg.Y_AXIS_MAX_INIT      # reset plot y axis max for the next session
        self.app.restore_mainmenu()
    
    def left_frame(self,event):
        self.app.view_plot.reset_plot()
        self.xmin -= self.xwidth
        self.index = self.index - (len(self.app.view_plot.ch1_x_data) - 1)
        
        self.app.view_plot.ch1_x_data = [i for i in self.app.view_plot.ch1_x_data_total if (i <= (self.xmin + self.xwidth) and i>= self.xmin)] 
        
        len_data = len(self.app.view_plot.ch1_x_data) # Finds the number of values to be displayed
        
        self.app.view_plot.ch1_y_data = self.app.view_plot.ch1_y_data_total[self.index:len_data+self.index]
        self.app.view_plot.ch2_x_data = self.app.view_plot.ch1_x_data # self.app.view_plot.ch2_x_data_total[self.index:len_data+self.index]
        self.app.view_plot.ch2_y_data = self.app.view_plot.ch2_y_data_total[self.index:len_data+self.index]
        
        
        self.app.view_plot.plotctrl.right_frame_button.Enable(True)
        
        if(0 > (self.index-len_data) ):
            self.app.view_plot.plotctrl.left_frame_button.Enable(False)
            

        self.app.view_plot.draw()
        
    def right_frame(self,event):
        self.app.view_plot.reset_plot()

        self.xmin += self.xwidth
        # Find new starting point in X data
        self.index = self.index + len(self.app.view_plot.ch1_x_data) - 1 
        
        self.app.view_plot.ch1_x_data = [i for i in self.app.view_plot.ch1_x_data_total if (i <= (self.xmin + self.xwidth) and i>= self.xmin)] 
        
        len_data = len(self.app.view_plot.ch1_x_data) # Finds the number of values to be displayed
        
        self.app.view_plot.ch1_y_data = self.app.view_plot.ch1_y_data_total[self.index:len_data+self.index]
        self.app.view_plot.ch2_x_data = self.app.view_plot.ch1_x_data #self.app.view_plot.ch2_x_data_total[self.index:len_data+self.index]
        self.app.view_plot.ch2_y_data = self.app.view_plot.ch2_y_data_total[self.index:len_data+self.index]
        
        
        self.app.view_plot.plotctrl.left_frame_button.Enable(True)
        
        if(len(self.app.view_plot.ch1_x_data_total) < (len_data+self.index*2) ):
            self.app.view_plot.plotctrl.right_frame_button.Enable(False)

           
        self.app.view_plot.draw()
        
    def manual_resize(self,event):
        self.app.view_plot.manual_y_axis = True
        
        self.app.view_plot.draw()
        
    def manual_radio(self,manual_radio_on):
        
        if not manual_radio_on:
            self.app.view_plot.manual_y_axis = False
            self.app.view_plot.draw()
            
# End of file "handlers.py"
